<?php
require __DIR__ . '/../vendor/autoload.php';

use PhpComposer\simhashCore\SimHash;
use Demo\ArticleModel;
use InvalidArgumentException;

// 初始化核心算法
$simhash = new SimHash();

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'dbname' => 'article_db',
    'username' => 'root',
    'password' => 'your_password'
];
$articleModel = new ArticleModel($dbConfig);

try {
    // 1. 准备外部传入的参数
    $articleData = [
        'idstr' => 'ext-ai-20240808-001',  // 外部系统传入的ID
        'title' => '人工智能发展现状',       // 外部传入的标题
        'content' => '人工智能作为计算机科学的分支，近年来应用领域不断扩大。',  // 外部传入的内容
        'source' => 'partner_api'           // 外部传入的来源
    ];
    
    // 2. 计算SimHash值
    $articleData['simhash'] = $simhash->calculate($articleData['content']);
    
    // 3. 存储文章（所有字段均为外部传入）
    $saveResult = $articleModel->saveArticle(
        $articleData['idstr'],
        $articleData['title'],
        $articleData['content'],
        $articleData['simhash'],
        $articleData['source']
    );
    
    echo $saveResult ? "文章存储成功（IDStr：{$articleData['idstr']}）\n" : "文章存储失败\n";
    
    // 4. 另一篇文章（全参数传入）
    $anotherArticle = [
        'idstr' => 'ext-ai-20240808-002',
        'title' => '人工智能技术应用',
        'content' => '人工智能作为计算机科学的重要分支，在多个领域得到了广泛应用。',
        'source' => 'partner_api',
        'simhash' => $simhash->calculate('人工智能作为计算机科学的重要分支，在多个领域得到了广泛应用。')
    ];
    
    $articleModel->saveArticle(
        $anotherArticle['idstr'],
        $anotherArticle['title'],
        $anotherArticle['content'],
        $anotherArticle['simhash'],
        $anotherArticle['source']
    );
    
    // 5. 查找相似文章
    $newArticle = [
        'idstr' => 'ext-ai-20240808-003',
        'title' => '人工智能应用领域',
        'content' => '作为计算机科学分支的人工智能，目前已在众多领域实现应用。',
        'source' => 'web'
    ];
    $newHash = $simhash->calculate($newArticle['content']);
    
    $articles = $articleModel->getAllSimhashes();
    $mostSimilar = null;
    $maxSimilarity = 0;
    
    foreach ($articles as $article) {
        $similarity = $simhash->getSimilarity($newHash, $article['simhash']);
        if ($similarity > $maxSimilarity) {
            $maxSimilarity = $similarity;
            $mostSimilar = $article;
        }
    }
    
    if ($mostSimilar) {
        echo "\n与《{$newArticle['title']}》最相似的文章：\n";
        echo "IDStr：{$mostSimilar['idstr']}\n";
        echo "标题：《{$mostSimilar['title']}》\n";
        echo "来源：{$mostSimilar['source']}\n";
        echo "相似度：{$maxSimilarity}%\n";
    }
} catch (InvalidArgumentException $e) {
    echo "参数错误：" . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "操作失败：" . $e->getMessage() . "\n";
}
